/** @format */

import {
  EditableFormInstance,
  EditableProTable,
  ProColumns,
} from "@ant-design/pro-components";
import { SelectProps, Tag } from "antd";
import { useRef, useState } from "react";
import WeekChooseOfDay from "./WeekChooseOfDay";
import WeekChooseOfTime from "./WeekChooseOfTime";

interface WeekChooseProps {
  value?: WeekChooseInput[];
  onChange?: (value: string) => void;
}

const WeeksData: SelectProps["options"] = [
  { label: "周一", value: "1" },
  { label: "周二", value: "2" },
  { label: "周三", value: "3" },
  { label: "周四", value: "4" },
  { label: "周五", value: "5" },
  { label: "周六", value: "6" },
  { label: "周日", value: "7" },
];

export type WeekChooseInput = {
  id: React.Key;
  days?: string;
  time?: string;
};

const WeekChoose: React.FC<WeekChooseProps> = (props) => {
  const { value, onChange } = props;
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [dataSource, setDataSource] = useState<readonly WeekChooseInput[]>(
    value ?? []
  );
  const editableFormRef = useRef<EditableFormInstance>();

  const weeksFilter = () => {
    let days: string[] = [];
    dataSource.forEach((element: WeekChooseInput) => {
      const elArr = element.days?.split(",");
      if (elArr) days.push(...elArr);
    });

    let WeeksDataFilter: SelectProps["options"] = [];

    for (let index = 0; index < WeeksData.length; index++) {
      const element = WeeksData[index];
      if (!days.includes(element.value as string))
        WeeksDataFilter.push(element);
    }

    return WeeksDataFilter;
  };

  const columns: ProColumns<WeekChooseInput>[] = [
    {
      title: "周",
      dataIndex: "days",
      width: "40%",
      formItemProps: {
        rules: [
          {
            required: true,
            message: "此项为必填项",
          },
        ],
      },
      renderFormItem: () => (
        <WeekChooseOfDay dataSource={weeksFilter()} onChange={(value) => {}} />
      ),
      render: (_, row) => {
        let arr = [];

        const rows = row.days?.split(",") ?? [];
        for (let index = 0; index < rows.length; index++) {
          const element = rows[index];

          for (let index = 0; index < WeeksData.length; index++) {
            const day = WeeksData[index];

            if (day.value == (element as unknown as number)) {
              arr.push(<Tag key={day.value}>{day.label}</Tag>);
              break;
            }
          }
        }

        return arr;
      },
    },
    {
      title: "运营时间",
      dataIndex: "time",
      width: "30%",
      formItemProps: {
        rules: [
          {
            required: true,
            message: "此项为必填项",
          },
        ],
      },
      renderFormItem: () => <WeekChooseOfTime />,
      render: (_, row) => {
        if (!row.time) return undefined;

        const times = row.time?.split("-");
        if (times.length < 2) return undefined;

        let start = times[0].split(":");
        start.pop();
        let end = times[1].split(":");
        end.pop();

        return (
          <div key="keya">
            {start.join(":")} ~ {end.join(":")}
          </div>
        );
      },
    },
    {
      title: "操作",
      fixed: "right",
      valueType: "option",
      render: (text, record, _, action) => [
        // <a
        //   key="editable"
        //   onClick={() => {
        //     action?.startEditable?.(record.id);
        //   }}>
        //   编辑
        // </a>,
        <a
          key="delete"
          onClick={() => {
            setDataSource(dataSource.filter((item) => item.id !== record.id));
            onChange?.(
              JSON.stringify(dataSource.filter((item) => item.id !== record.id))
            );
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  return (
    <EditableProTable<WeekChooseInput>
      rowKey="id"
      editableFormRef={editableFormRef}
      toolBarRender={false}
      columns={columns}
      value={dataSource}
      onChange={(value) => {
        setDataSource(value);
        onChange?.(JSON.stringify(value));
      }}
      recordCreatorProps={{
        position: "bottom",
        record: (_, data) => {
          return { id: (Math.random() * 1000000).toFixed(0) };
        },
      }}
      editable={{
        type: "multiple",
        editableKeys,
        onChange: setEditableRowKeys,
        actionRender: (row, config, dom) => [dom.save, dom.cancel],
      }}
    />
  );
};

export default WeekChoose;
